﻿using Microsoft.AspNetCore.Http;

namespace Infrastructure.Common
{
    /// <summary>
    /// 上传图片
    /// </summary>
    public static class UpLoadHelpers
    {
        //上传文件
        public static string UpLoad(IFormFile file)
        {
            if (file == null)
            {
                return "-1";//请选择文件上传
            }
            if (file.Length == 0)
            {
                return "-2";//文件大小不能为0KB
            }
            if (file.Length / 1024 / 1024 > 2)
            {
                return "-3";//文件大小不能大于2MB
            }
            if (!file.ContentType.StartsWith("image/"))
            {
                return "-4";//请上传图片格式文件
            }
            //判断文件夹是否存在，不存在则重新创建
            string datestr = DateTime.Now.ToString("yyyyMMdd");
            if (!Directory.Exists("wwwroot/images/" + datestr))
            {
                Directory.CreateDirectory("wwwroot/images/" + datestr);
            }
            //生成新的文件名
            string newFile = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
            //虚拟路径
            string path = "wwwroot/images/" + datestr + "/" + newFile;
            if (System.IO.File.Exists(path))
            {
                return "-5";
            }
            //上传
            using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
            {
                file.CopyTo(fs);
                fs.Close();
            }
            return "images/"+datestr + "/" + newFile;
        }


    }
}